from celery import shared_task #: Celery 装饰器，用于创建可被任何应用共享的任务
import json
from utils.myredis import r
from mytools.baiduapi import baiduapi
__all__ = ['bdcardmes', 'add', 'process_insurance_application']

@shared_task
def bdcardmes():#
    # 从redis list中获取10条信息
    # 调用百度api接口
    # 将结果存入redis
    blist = r.list_lrange('baiduurllist', 0, 10)
    if blist:
        for i in blist:
            picurl = i.decode()
            # 调用百度api接口
            mes = baiduapi.idcard(picurl)
            # 存入redis {"name":"zs","code":"234234"}
            r.set_str(picurl, json.dumps(mes))
            r.list_del('baiduurllist', picurl)

    print("调用百度api接口")




@shared_task
def add(x, y):
    print(f"计算 {x} + {y}")
    return x + y
@shared_task
def process_insurance_application(input_data):
    """
    异步处理保险申请（完全保持你原有的处理逻辑）
    参数:
        input_data: 包含所有申请数据的字典
    返回:
        与原有InsuranceProcessView相同的响应结构
    """
    from mytools.my_agent import agent_executor
    import json

    try:
        # 直接复制你原有的处理逻辑
        agent_input = {
            "input": (
                f"请处理投保申请：\n"
                f"投保人：{input_data['aname']}({input_data['acard_id']})\n"
                f"被保人：{input_data['bname']}({input_data['bcard_id']})\n"
                f"联系方式：{input_data['phone']}\n"
                f"关系：{input_data['relationship']}\n"
                f"生效日期：{input_data.get('effective_date', '默认7天后')}\n"
                f"保险期限：{input_data.get('term_years', 1)}年\n"
                f"订单编号: {input_data.get('order_id', '')}"
            ),
            "chat_history": input_data.get('chat_history', [])
        }

        # 执行代理流程
        agent_response = agent_executor.invoke(agent_input)

        # 返回与视图相同的结构
        if "审核通过" in agent_response["output"]:
            return {
                "status": "success",
                "data": {
                    "contract_id": agent_response.get("contract_id", ""),
                    "review_result": json.loads(agent_response["output"]),
                    "execution_steps": agent_response.get("intermediate_steps", [])
                }
            }
        else:
            return {
                "status": "review_failed",
                "details": agent_response["output"],
                "suggestions": extract_suggestions(agent_response)
            }

    except Exception as e:
        return {
            "status": "error",
            "message": str(e)
        }


def extract_suggestions(agent_response):
    """直接从你的视图代码复制过来的建议提取逻辑"""
    try:
        output = agent_response["output"]
        if "改进建议" in output:
            return [s.strip() for s in output.split("改进建议:")[1].split("\n") if s.strip()]
        return []
    except:
        return []